package cn.yujiago.springboot.controller;

import cn.yujiago.springboot.config.Constants;
import cn.yujiago.springboot.entity.UserDO;
import cn.yujiago.springboot.pojo.BackAdminResult;
import cn.yujiago.springboot.pojo.LayuiTableResult;
import cn.yujiago.springboot.realm.PhoneToken;
import cn.yujiago.springboot.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    // 用户名密码登录
    @PostMapping("/dologin")
    @ResponseBody
    public BackAdminResult dologin(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) throws AuthenticationException {

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        Subject subject = SecurityUtils.getSubject();

        subject.login(token);
        UserDO user = (UserDO) subject.getPrincipal();
        session.setAttribute(Constants.LOGIN_ADMIN_KEY, user);
        subject.getSession().setAttribute(Constants.LOGIN_ADMIN_KEY, user);
        return BackAdminResult.build(0, "登录成功");

    }

    // 检查手机号是否存在
    @RequestMapping("/checkPhone")
    @ResponseBody
    public BackAdminResult checkPhone(@RequestParam("phone") String phone, @RequestParam("type") String type){

        boolean isExists = userService.checkPhoneExists(phone);

        if(isExists && "login".equals(type)){
            return BackAdminResult.build(0, "手机号可登陆");
        } else if(!isExists && "register".equals(type)){
            return BackAdminResult.build(0, "手机号可注册");
        } else if(!isExists && "login".equals(type)){
            return BackAdminResult.build(1, "手机号未注册");
        } else{
            return BackAdminResult.build(1, "手机号已注册");
        }
    }

    @RequestMapping("/checkUsername")
    @ResponseBody
    public BackAdminResult checkUsername(@RequestParam("username") String username){

        UserDO user = userService.getUser(username);

        if(user == null){
            return BackAdminResult.build(0, "用户名可注册");
        }else{
            return BackAdminResult.build(1, "用户名已注册");
        }
    }

    // 发送短信验证码
    @RequestMapping("/sendMessageCode")
    @ResponseBody
    public BackAdminResult sendMessageCode(@RequestParam("phone") String phone, @RequestParam("type") String type, HttpSession session){

        boolean isSuccess = userService.sendMessageCode(phone, session);

        if(isSuccess){
            return BackAdminResult.build(0, "成功发送验证码");
        }else{
            return BackAdminResult.build(1, "发送验证码失败");
        }
    }

    // 使用手机号和短信验证码登录
    @RequestMapping("/plogin")
    @ResponseBody
    public BackAdminResult pLogin(@RequestParam("phone") String phone, @RequestParam("code") String code, HttpSession session){

        // 根据phone从session中取出发送的短信验证码，并与用户输入的验证码比较
        String messageCode = (String) session.getAttribute(phone);

        if(StringUtils.isNoneBlank(messageCode) && messageCode.equals(code)){

            PhoneToken token = new PhoneToken(phone);

            Subject subject = SecurityUtils.getSubject();

            subject.login(token);
            UserDO user = (UserDO) subject.getPrincipal();
            session.setAttribute(Constants.LOGIN_ADMIN_KEY, user);
            return BackAdminResult.build(0, "登录成功");

        }else{
            return BackAdminResult.build(2, "验证码错误");
        }
    }

    // 使用手机号注册
    @RequestMapping("/pRegister")
    @ResponseBody
    public BackAdminResult pRegister(UserDO user, @RequestParam("code") String code, HttpSession session){
        return userService.register(user, code, session);
    }

    @GetMapping("/excelExport")
    public void excelExport(HttpServletRequest request, HttpServletResponse response){
        userService.excelExport(request, response);
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        SecurityUtils.getSubject().logout();
        return "redirect:/page/anon/login";
    }

    @RequestMapping("/getUserByDeptId")
    @ResponseBody
    public LayuiTableResult<UserDO> getUserByDeptId(@RequestParam(value = "deptId", defaultValue = "0") Long deptId, @RequestParam("page") int page, @RequestParam("limit") int limit){
        return userService.getUserByDeptId(deptId, page, limit);
    }

}
